package com.hotacorp.opencloud.gateway.filter;

import java.io.UnsupportedEncodingException;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.NettyWriteResponseFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.MediaType;
import org.springframework.web.server.ServerWebExchange;

import com.alibaba.fastjson.JSONObject;
import com.hotacorp.opencloud.common.commdata.Result;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/**
 * 对没有body内容的返回包添加标志内容，当gateway调用服务时，由于服务发生错误等情况，如果gateway不对返回给用户的数据包进行更正，那么返回给用户的数据包将不会包含标准的返回信息
 * @author lwg
 *
 */
//@Component
public class WrapperResponseFilter implements GlobalFilter, Ordered {

	@Override
	public int getOrder() {
		return NettyWriteResponseFilter.LOWEST_PRECEDENCE - 1;
	}

	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		//System.out.println("执行");
		if (!exchange.getResponse().getStatusCode().is2xxSuccessful()) {
			Result<String> ddddd = new Result<String>("", exchange.getResponse().getStatusCode().value(), exchange.getResponse().getStatusCode().getReasonPhrase());
			String string = JSONObject.toJSONString(ddddd);
			byte[] bodyStr = new byte[0];
			try {
				bodyStr = string.getBytes("UTF-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			DataBufferFactory sss= exchange.getResponse().bufferFactory();
			DataBuffer bodyDataBuffer = sss.wrap(bodyStr);
            Flux<DataBuffer> bodyFlux = Flux.just(bodyDataBuffer);
            
            exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
            return exchange.getResponse().writeWith(bodyFlux).then(Mono.fromRunnable(() ->{exchange.getResponse().setComplete();}));
		} else {
			return chain.filter(exchange);
		}
	}

}
